package com.easychat.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.easychat.constants.Constants;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.enums.AppUpdateFileTypeEnum;
import com.easychat.entity.enums.AppUpdateStatusEnum;
import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.exception.BusinessException;
import org.springframework.stereotype.Service;

import com.easychat.entity.enums.PageSize;
import com.easychat.entity.query.AppUpdateQuery;
import com.easychat.entity.po.AppUpdate;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.entity.query.SimplePage;
import com.easychat.mappers.AppUpdateMapper;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.StringTools;
import org.springframework.web.multipart.MultipartFile;


/**
 *  业务接口实现
 */
@Service("appUpdateService")
public class AppUpdateServiceImpl implements AppUpdateService {

	@Resource
	private AppUpdateMapper<AppUpdate, AppUpdateQuery> appUpdateMapper;
	@Resource
	private AppConfig appConfig;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<AppUpdate> findListByParam(AppUpdateQuery param) {
		return this.appUpdateMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(AppUpdateQuery param) {
		return this.appUpdateMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<AppUpdate> findListByPage(AppUpdateQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<AppUpdate> list = this.findListByParam(param);
		PaginationResultVO<AppUpdate> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(AppUpdate bean) {
		return this.appUpdateMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<AppUpdate> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<AppUpdate> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(AppUpdate bean, AppUpdateQuery param) {
		StringTools.checkParam(param);
		return this.appUpdateMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(AppUpdateQuery param) {
		StringTools.checkParam(param);
		return this.appUpdateMapper.deleteByParam(param);
	}

	/**
	 * 根据Id获取对象
	 */
	@Override
	public AppUpdate getAppUpdateById(Integer id) {
		return this.appUpdateMapper.selectById(id);
	}

	/**
	 * 根据Id修改
	 */
	@Override
	public Integer updateAppUpdateById(AppUpdate bean, Integer id) {
		return this.appUpdateMapper.updateById(bean, id);
	}

	/**
	 * 根据Id删除
	 */
	@Override
	public Integer deleteAppUpdateById(Integer id) {
		//在删除时，只有在未发布状态时，可进行删除
		AppUpdate dbInfo = appUpdateMapper.selectById(id);
		AppUpdateStatusEnum dbStatusEnum = AppUpdateStatusEnum.getByType(dbInfo.getStatus());
		if (dbStatusEnum != AppUpdateStatusEnum.INIT) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		return this.appUpdateMapper.deleteById(id);
	}

	/**
	 * 根据Version获取对象
	 */
	@Override
	public AppUpdate getAppUpdateByVersion(String version) {
		return this.appUpdateMapper.selectByVersion(version);
	}

	/**
	 * 根据Version修改
	 */
	@Override
	public Integer updateAppUpdateByVersion(AppUpdate bean, String version) {
		return this.appUpdateMapper.updateByVersion(bean, version);
	}

	/**
	 * 根据Version删除
	 */
	@Override
	public Integer deleteAppUpdateByVersion(String version) {
		return this.appUpdateMapper.deleteByVersion(version);
	}

	/**
	 * 保存更新
	 * @param appUpdate 更新信息
	 * @param file 更新文件
	 */
	@Override
	public void saveUpdate(AppUpdate appUpdate, MultipartFile file) throws IOException {
		AppUpdateFileTypeEnum typeEnum = AppUpdateFileTypeEnum.getByType(appUpdate.getFileType());
		if (typeEnum == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		//在修改时，只有在未发布状态时，可进行修改
		if (appUpdate.getId() != null) {
			AppUpdate dbInfo = appUpdateMapper.selectById(appUpdate.getId());
			AppUpdateStatusEnum dbStatusEnum = AppUpdateStatusEnum.getByType(dbInfo.getStatus());
			if (dbStatusEnum != AppUpdateStatusEnum.INIT) {
				throw new BusinessException(ResponseCodeEnum.CODE_600);
			}
		}
		//新版本的版本号要比以前的大
		//查最新数据的版本号(最新数据id是最大的)
		AppUpdateQuery appUpdateQuery = new AppUpdateQuery();
		appUpdateQuery.setOrderBy("id desc");//按id降序
		appUpdateQuery.setSimplePage(new SimplePage(0,1));//取第一条
		List<AppUpdate> appUpdates = appUpdateMapper.selectList(appUpdateQuery);
		if (appUpdates != null && !appUpdates.isEmpty()) {
			//取第一条
			AppUpdate latestUpdate = appUpdates.get(0);
			//将"."去掉，并转成Long类型比大小
			Long dbVersion = Long.parseLong(latestUpdate.getVersion().replace(".", ""));
			Long curVersion = Long.parseLong(appUpdate.getVersion().replace(".", ""));
			if (appUpdate.getId() == null && curVersion <= dbVersion) {
				//id为空是新增操作
				throw new BusinessException("当前版本必须大于历史版本");
			}
			if (appUpdate.getId() != null && !appUpdate.getId().equals(latestUpdate.getId()) && curVersion >= dbVersion) {
				//id不为空是修改操作
				//!appUpdate.getId().equals(latestUpdate.getId())说明修改的不是最新的数据(修改的是历史版本)
				//如果修改后的版本curVersion(历史版本) >= 最新数据的版本dbVersion，报错
				throw new BusinessException("当前版本必须大于历史版本");
			}
			//修改时，版本号不能重复
			AppUpdate versionDbInfo = appUpdateMapper.selectByVersion(appUpdate.getVersion());
			if (appUpdate.getId() != null && versionDbInfo != null && !appUpdate.getId().equals(versionDbInfo.getId())) {
				throw new BusinessException("版本号已经存在");
			}
		}
		if (appUpdate.getId() == null) {
			//新增操作
			appUpdate.setStatus(AppUpdateStatusEnum.INIT.getType());
			appUpdate.setCreateTime(new Date());
			appUpdateMapper.insert(appUpdate);
		} else {
			//修改操作
//			appUpdate.setStatus(null);//不能修改发布状态
//			appUpdate.setGrayscaleUid(null);//不能修改灰度uid
			appUpdateMapper.updateById(appUpdate, appUpdate.getId());
		}
		if (file != null) {
			File appUpdateFolder = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER);
			if (!appUpdateFolder.exists()) {
				appUpdateFolder.mkdirs();
			}
			file.transferTo(new File(appUpdateFolder.getPath() + "/" + appUpdate.getId() + Constants.APP_UPDATE_EXTENSION));
		}
	}

	/**
	 * 发布更新
	 * @param id
	 * @param status 状态 1 灰度发布 2 全网发布
	 * @param grayscaleUid 灰度uid
	 * @return
	 */
	@Override
	public void postUpdate(Integer id, Integer status, String grayscaleUid) {
		AppUpdateStatusEnum statusEnum = AppUpdateStatusEnum.getByType(status);
		if (statusEnum == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		if (statusEnum == AppUpdateStatusEnum.GRAYSCALE && StringTools.isEmpty(grayscaleUid)) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		if (statusEnum != AppUpdateStatusEnum.GRAYSCALE) {
			grayscaleUid = "";
		}
		AppUpdate appUpdate = new AppUpdate();
		appUpdate.setStatus(status);
		appUpdate.setGrayscaleUid(grayscaleUid);
		appUpdateMapper.updateById(appUpdate, id);
	}

	/**
	 * 获取最新更新
	 * @param appVersion 客户端版本
	 * @param uid 用户id
	 * @return
	 */
	@Override
	public AppUpdate getLatestUpdate(String appVersion, String uid) {
		return appUpdateMapper.selectLatestUpdate(appVersion, uid);
	}
}